import React, { useState, useEffect } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Upload,
  message,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Tree,
  Row,
  Col,
  Typography,
  Tooltip,
  Progress,
  Spin,
  Dropdown,
  Menu,
  Empty,
  Divider,
  Alert,
  Badge,
  Tabs,
  List,
  Avatar,
  Statistic,
} from "antd";
import {
  UploadOutlined,
  FolderOutlined,
  FileOutlined,
  DeleteOutlined,
  EditOutlined,
  DownloadOutlined,
  ShareAltOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  MoreOutlined,
  SearchOutlined,
  FilterOutlined,
  BookOutlined,
  ExperimentOutlined,
  FileTextOutlined,
  FolderAddOutlined,
  CloudUploadOutlined,
  ReloadOutlined,
  StarOutlined,
  StarFilled,
} from "@ant-design/icons";
import type { UploadProps, UploadFile } from "antd";
import type { DataNode } from "antd/es/tree";
import styled from "styled-components";
import type { TableRowSelection } from "antd/es/table/interface";
import type { Key } from "react";
import {
  resourceAPI,
  Resource as ResourceType,
} from "../../../services/resourceService";
import { COURSES, TEACHERS } from "../../../utils/mockData";

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { DirectoryTree } = Tree;
const { confirm } = Modal;
const { TabPane } = Tabs;

// 类型定义
interface Resource {
  id: string;
  name: string;
  type: "ppt" | "pdf" | "doc" | "folder" | "video" | "image";
  size: string;
  uploadTime: string;
  category: "课件" | "实验资料" | "试题资料" | "视频资料" | "其他";
  courseId?: string;
  courseName?: string;
  downloads: number;
  shared: boolean;
  description?: string;
  progress?: number;
  url?: string;
  tags?: string[];
  isFavorite?: boolean;
}

interface Course {
  id: string;
  name: string;
  code: string;
  teacher: string;
  studentCount: number;
}

interface TreeNode extends DataNode {
  title: string;
  key: string;
  children?: TreeNode[];
  isLeaf?: boolean;
  courseId?: string;
}

interface FormValues {
  name: string;
  category: Resource["category"];
  courseId?: string;
  description?: string;
  tags?: string[];
}

// 样式组件
const StyledCard = styled(Card)`
  .ant-card-body {
    padding: 24px;
  }
`;

const ResourceIcon = styled.span<{ type: Resource["type"] }>`
  .anticon {
    font-size: 16px;
    margin-right: 8px;
    color: ${(props) => {
      switch (props.type) {
        case "ppt":
          return "#FF9900";
        case "pdf":
          return "#FF0000";
        case "doc":
          return "#0066CC";
        case "folder":
          return "#52C41A";
        case "video":
          return "#722ED1";
        case "image":
          return "#13C2C2";
        default:
          return "#666";
      }
    }};
  }
`;

const UploadArea = styled.div`
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  padding: 40px;
  text-align: center;
  background: #fafafa;
  transition: border-color 0.3s;
  
  &:hover {
    border-color: #1890ff;
    background: #f0f8ff;
  }
`;

// 使用与课程管理界面一致的课程数据
const mockCourses: Course[] = COURSES.map(course => ({
  id: course.id,
  name: course.name,
  code: course.code,
  teacher: course.teacher.name,
  studentCount: course.currentStudents,
}));

// 扩展的模拟资源数据，与课程管理界面对应
const mockResources: Resource[] = [
  // 数据结构与算法课程资源
  {
    id: "1",
    name: "数据结构基础.pptx",
    type: "ppt",
    size: "3.2MB",
    uploadTime: "2024-01-15",
    category: "课件",
    courseId: "c1",
    courseName: "数据结构与算法",
    downloads: 156,
    shared: true,
    description: "数据结构基础概念教学课件",
    tags: ["基础", "概念", "重点"],
    isFavorite: true,
  },
  {
    id: "2",
    name: "算法实验指导书.docx",
    type: "doc",
    size: "2.8MB",
    uploadTime: "2024-01-16",
    category: "实验资料",
    courseId: "c1",
    courseName: "数据结构与算法",
    downloads: 234,
    shared: false,
    description: "数据结构与算法实验指导书",
    tags: ["实验", "算法", "指导"],
    isFavorite: true,
  },
  {
    id: "3",
    name: "期末考试题库.docx",
    type: "doc",
    size: "1.5MB",
    uploadTime: "2024-01-17",
    category: "试题资料",
    courseId: "c1",
    courseName: "数据结构与算法",
    downloads: 189,
    shared: false,
    description: "数据结构与算法期末考试题库",
    tags: ["考试", "题库", "期末"],
    isFavorite: false,
  },
  {
    id: "4",
    name: "排序算法演示.mp4",
    type: "video",
    size: "25.6MB",
    uploadTime: "2024-01-18",
    category: "视频资料",
    courseId: "c1",
    courseName: "数据结构与算法",
    downloads: 123,
    shared: true,
    description: "各种排序算法的动态演示视频",
    tags: ["排序", "算法", "演示"],
    isFavorite: false,
  },

  // Java程序设计课程资源
  {
    id: "5",
    name: "Java基础语法.pptx",
    type: "ppt",
    size: "2.5MB",
    uploadTime: "2024-01-15",
    category: "课件",
    courseId: "c2",
    courseName: "Java程序设计",
    downloads: 145,
    shared: true,
    description: "Java基础语法教学课件",
    tags: ["基础", "语法", "重点"],
    isFavorite: true,
  },
  {
    id: "6",
    name: "面向对象编程指南.pdf",
    type: "pdf",
    size: "4.2MB",
    uploadTime: "2024-01-16",
    category: "课件",
    courseId: "c2",
    courseName: "Java程序设计",
    downloads: 167,
    shared: true,
    description: "Java面向对象编程详细指南",
    tags: ["面向对象", "编程", "指南"],
    isFavorite: false,
  },
  {
    id: "7",
    name: "Java实验项目.zip",
    type: "folder",
    size: "18.5MB",
    uploadTime: "2024-01-17",
    category: "实验资料",
    courseId: "c2",
    courseName: "Java程序设计",
    downloads: 89,
    shared: true,
    description: "Java程序设计实验项目资料包",
    tags: ["实验", "项目", "Java"],
    isFavorite: true,
  },
  {
    id: "8",
    name: "Java编程技巧.mp4",
    type: "video",
    size: "32.1MB",
    uploadTime: "2024-01-18",
    category: "视频资料",
    courseId: "c2",
    courseName: "Java程序设计",
    downloads: 98,
    shared: false,
    description: "Java编程技巧与最佳实践",
    tags: ["技巧", "最佳实践", "视频"],
    isFavorite: false,
  },

  // 数据库原理课程资源
  {
    id: "9",
    name: "数据库设计原理.pptx",
    type: "ppt",
    size: "3.8MB",
    uploadTime: "2024-01-15",
    category: "课件",
    courseId: "c3",
    courseName: "数据库原理",
    downloads: 134,
    shared: true,
    description: "数据库设计原理教学课件",
    tags: ["设计", "原理", "重点"],
    isFavorite: true,
  },
  {
    id: "10",
    name: "SQL实验指导书.docx",
    type: "doc",
    size: "2.1MB",
    uploadTime: "2024-01-16",
    category: "实验资料",
    courseId: "c3",
    courseName: "数据库原理",
    downloads: 178,
    shared: false,
    description: "SQL语言实验指导书",
    tags: ["SQL", "实验", "指导"],
    isFavorite: false,
  },
  {
    id: "11",
    name: "数据库设计实验.zip",
    type: "folder",
    size: "15.6MB",
    uploadTime: "2024-01-17",
    category: "实验资料",
    courseId: "c3",
    courseName: "数据库原理",
    downloads: 67,
    shared: true,
    description: "数据库设计实验资料包",
    tags: ["数据库", "设计", "实验"],
    isFavorite: true,
  },
  {
    id: "12",
    name: "数据库优化技术.mp4",
    type: "video",
    size: "28.9MB",
    uploadTime: "2024-01-18",
    category: "视频资料",
    courseId: "c3",
    courseName: "数据库原理",
    downloads: 76,
    shared: true,
    description: "数据库性能优化技术讲解",
    tags: ["优化", "性能", "技术"],
    isFavorite: false,
  },

  // 未分类文件
  {
    id: "13",
    name: "教学大纲模板.docx",
    type: "doc",
    size: "1.2MB",
    uploadTime: "2024-01-19",
    category: "其他",
    courseId: undefined,
    courseName: undefined,
    downloads: 45,
    shared: true,
    description: "通用教学大纲模板",
    tags: ["模板", "大纲"],
    isFavorite: false,
  },
  {
    id: "14",
    name: "教学参考资料.pdf",
    type: "pdf",
    size: "5.6MB",
    uploadTime: "2024-01-20",
    category: "其他",
    courseId: undefined,
    courseName: undefined,
    downloads: 32,
    shared: false,
    description: "通用教学参考资料",
    tags: ["参考", "资料"],
    isFavorite: true,
  },
];

const TeacherResources: React.FC = () => {
  const [resources, setResources] = useState<Resource[]>(mockResources);
  const [courses, setCourses] = useState<Course[]>(mockCourses);
  const [loading, setLoading] = useState(false);
  const [resourcesLoading, setResourcesLoading] = useState(false);

  // 模态框状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isUploadModalVisible, setIsUploadModalVisible] = useState(false);
  const [selectedResource, setSelectedResource] = useState<string | null>(null);
  const [form] = Form.useForm();
  const [uploadForm] = Form.useForm();

  // 上传状态
  const [uploadingFiles, setUploadingFiles] = useState<{
    [key: string]: number;
  }>({});
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [selectedCourse, setSelectedCourse] = useState<string | null>(null);

  // 预览状态
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewResource, setPreviewResource] = useState<Resource | null>(null);
  const [previewLoading, setPreviewLoading] = useState(false);

  // 选择状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [selectedTreeKey, setSelectedTreeKey] = useState<string>("");

  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: mockResources.length,
  });

  // 搜索和筛选状态
  const [searchParams, setSearchParams] = useState({
    keyword: "",
    category: "",
    type: "",
    courseId: "",
  });

  // 视图状态
  const [viewMode, setViewMode] = useState<"list" | "grid">("list");
  const [activeTab, setActiveTab] = useState("all");

  // 初始化数据
  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    setLoading(true);
    try {
      // 使用模拟数据
      setResources(mockResources);
      setCourses(mockCourses);
      setPagination(prev => ({
        ...prev,
        total: mockResources.length,
      }));
    } catch (error) {
      console.error("初始化数据失败:", error);
      message.error("数据加载失败，请刷新页面重试");
    } finally {
      setLoading(false);
    }
  };

  // 加载资源列表
  const loadResources = async (params?: any) => {
    setResourcesLoading(true);
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 使用模拟数据进行筛选
      let filteredResources = [...mockResources];
      
      if (params?.keyword) {
        filteredResources = filteredResources.filter(resource =>
          resource.name.toLowerCase().includes(params.keyword.toLowerCase()) ||
          resource.description?.toLowerCase().includes(params.keyword.toLowerCase()) ||
          resource.courseName?.toLowerCase().includes(params.keyword.toLowerCase())
        );
      }
      
      if (params?.category) {
        filteredResources = filteredResources.filter(resource =>
          resource.category === params.category
        );
      }
      
      if (params?.type) {
        filteredResources = filteredResources.filter(resource =>
          resource.type === params.type
        );
      }

      if (params?.courseId) {
        filteredResources = filteredResources.filter(resource =>
          resource.courseId === params.courseId
        );
      }
      
      setResources(filteredResources);
      setPagination(prev => ({
        ...prev,
        total: filteredResources.length,
      }));
    } catch (error) {
      console.error("加载资源失败:", error);
      message.error("资源加载失败");
      setResources([]);
    } finally {
      setResourcesLoading(false);
    }
  };

  // 搜索资源
  const handleSearch = (values: any) => {
    setSearchParams(values);
    setPagination((prev) => ({ ...prev, current: 1 }));
    loadResources(values);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({ keyword: "", category: "", type: "", courseId: "" });
    setPagination((prev) => ({ ...prev, current: 1 }));
    loadResources({ keyword: "", category: "", type: "", courseId: "" });
  };

  // 显示新建文件夹模态框
  const showModal = () => {
    setSelectedResource(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  // 显示上传模态框
  const showUploadModal = () => {
    uploadForm.resetFields();
    // 如果左侧选择了课程，默认设置该课程
    if (selectedCourse) {
      uploadForm.setFieldsValue({ courseId: selectedCourse });
    }
    setIsUploadModalVisible(true);
  };

  // 处理新建文件夹确认
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const newResource: Resource = {
        id: Date.now().toString(),
        name: values.name,
        type: "folder",
        size: "0KB",
        uploadTime: new Date().toISOString().split('T')[0],
        category: values.category,
        courseId: values.courseId,
        courseName: courses.find(c => c.id === values.courseId)?.name,
        downloads: 0,
        shared: false,
        description: values.description,
        tags: values.tags || [],
      };
      
      setResources(prev => [...prev, newResource]);
      setIsModalVisible(false);
      form.resetFields();
      message.success("文件夹创建成功！");
    } catch (error) {
      console.error("创建文件夹失败:", error);
    }
  };

  // 处理上传确认
  const handleUploadOk = async () => {
    try {
      const values = await uploadForm.validateFields();
      // 这里可以处理上传逻辑
      setIsUploadModalVisible(false);
      uploadForm.resetFields();
      message.success("文件上传成功！");
    } catch (error) {
      console.error("上传失败:", error);
    }
  };

  // 处理取消
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 处理上传取消
  const handleUploadCancel = () => {
    setIsUploadModalVisible(false);
    uploadForm.resetFields();
  };

  // 删除资源
  const handleDelete = (id: string) => {
    confirm({
      title: "确认删除",
      content: "确定要删除这个资源吗？删除后无法恢复。",
      onOk: () => {
        setResources(prev => prev.filter(r => r.id !== id));
        message.success("资源删除成功");
      },
    });
  };

  // 分享资源
  const handleShare = async (id: string, currentShared: boolean) => {
    try {
      setResources(prev => 
        prev.map(r => 
          r.id === id ? { ...r, shared: !currentShared } : r
        )
      );
      message.success(currentShared ? "取消分享成功" : "分享成功");
    } catch (error) {
      console.error("分享操作失败:", error);
      message.error("操作失败，请重试");
    }
  };

  // 收藏资源
  const handleFavorite = async (id: string, currentFavorite: boolean) => {
    try {
      setResources(prev => 
        prev.map(r => 
          r.id === id ? { ...r, isFavorite: !currentFavorite } : r
        )
      );
      message.success(currentFavorite ? "取消收藏成功" : "收藏成功");
    } catch (error) {
      console.error("收藏操作失败:", error);
      message.error("操作失败，请重试");
    }
  };

  // 上传配置
  const uploadProps: UploadProps = {
    name: "file",
    multiple: true,
    action: "/api/upload", // 这里应该指向Python后端的上传接口
    headers: {
      authorization: "authorization-text",
    },
    data: (file) => {
      const formData = uploadForm.getFieldsValue();
      return {
        category: formData.category || "课件",
        courseId: formData.courseId || null, // 如果未选择课程，传null表示未分类
        description: formData.description || "",
        tags: formData.tags || [],
      };
    },
    onChange(info) {
      const { status } = info.file;
      if (status === "uploading") {
        setUploadingFiles(prev => ({
          ...prev,
          [info.file.name]: info.file.percent || 0,
        }));
      } else if (status === "done") {
        setUploadingFiles(prev => {
          const newState = { ...prev };
          delete newState[info.file.name];
          return newState;
        });
        message.success(`${info.file.name} 上传成功`);
        
        // 模拟添加新上传的文件到列表
        const formData = uploadForm.getFieldsValue();
        const newResource: Resource = {
          id: Date.now().toString(),
          name: info.file.name,
          type: info.file.name.endsWith('.pdf') ? 'pdf' : 
                info.file.name.endsWith('.ppt') || info.file.name.endsWith('.pptx') ? 'ppt' : 
                info.file.name.endsWith('.mp4') || info.file.name.endsWith('.avi') ? 'video' :
                info.file.name.endsWith('.jpg') || info.file.name.endsWith('.png') ? 'image' : 'doc',
          size: `${((info.file.size || 0) / 1024 / 1024).toFixed(1)}MB`,
          uploadTime: new Date().toISOString().split('T')[0],
          category: formData.category || "课件",
          courseId: formData.courseId || undefined, // 如果未选择课程，则为undefined（未分类）
          courseName: formData.courseId ? courses.find(c => c.id === formData.courseId)?.name : undefined,
          downloads: 0,
          shared: false,
          description: formData.description,
          tags: formData.tags || [],
        };
        setResources(prev => [...prev, newResource]);
      } else if (status === "error") {
        setUploadingFiles(prev => {
          const newState = { ...prev };
          delete newState[info.file.name];
          return newState;
        });
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onDrop(e) {
      console.log("Dropped files", e.dataTransfer.files);
    },
    // 确保上传成功的处理
    beforeUpload: (file) => {
      // 这里可以添加文件类型和大小验证
      const isValidType = [
        'application/pdf',
        'application/vnd.ms-powerpoint',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'video/mp4',
        'image/jpeg',
        'image/png',
        'text/plain'
      ].includes(file.type);
      
      if (!isValidType) {
        message.error('不支持的文件类型！');
        return false;
      }
      
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isLt50M) {
        message.error('文件大小不能超过50MB！');
        return false;
      }
      
      return true;
    },
  };

  // 动态生成树形数据（基于课程和分类）
  const generateTreeData = () => {
    const treeData: TreeNode[] = [];

    // 添加"未分类文件"节点
    const uncategorizedResources = resources.filter(r => !r.courseId);
    if (uncategorizedResources.length > 0) {
      const uncategorizedNode: TreeNode = {
        title: `📁 未分类文件 (${uncategorizedResources.length})`,
        key: "uncategorized",
        children: []
      };

      // 按分类组织未分类的资源
      const categories = ["课件", "实验资料", "试题资料", "视频资料", "其他"];
      categories.forEach(category => {
        const categoryResources = uncategorizedResources.filter(r => r.category === category);
        if (categoryResources.length > 0) {
          const categoryNode: TreeNode = {
            title: `${category} (${categoryResources.length})`,
            key: `uncategorized-${category}`,
            children: categoryResources.map((resource, index) => ({
              title: resource.name,
              key: `resource-${resource.id}`,
              isLeaf: true,
            }))
          };
          uncategorizedNode.children!.push(categoryNode);
        }
      });

      treeData.push(uncategorizedNode);
    }

    // 按课程分组
    courses.forEach(course => {
      const courseResources = resources.filter(r => r.courseId === course.id);
      const courseNode: TreeNode = {
        title: `${course.name} (${courseResources.length})`,
        key: `course-${course.id}`,
        courseId: course.id,
        children: []
      };

      // 按分类组织课程下的资源
      const categories = ["课件", "实验资料", "试题资料", "视频资料", "其他"];
      categories.forEach(category => {
        const categoryResources = courseResources.filter(r => r.category === category);
        if (categoryResources.length > 0) {
          const categoryNode: TreeNode = {
            title: `${category} (${categoryResources.length})`,
            key: `course-${course.id}-${category}`,
            courseId: course.id,
            children: categoryResources.map((resource, index) => ({
              title: resource.name,
              key: `resource-${resource.id}`,
              isLeaf: true,
              courseId: course.id,
            }))
          };
          courseNode.children!.push(categoryNode);
        }
      });

      if (courseNode.children!.length > 0) {
        treeData.push(courseNode);
      }
    });

    return treeData;
  };

  // 获取树形数据
  const getTreeData = () => {
    const treeData = generateTreeData();
    if (treeData.length > 0) {
      return treeData;
    }

    // 默认树形结构
    return [
      {
        title: "📚 我的课程",
        key: "courses",
        children: [{ title: "暂无课程资源", key: "empty", disabled: true }],
      },
    ];
  };

  // 处理树节点选择
  const handleTreeSelect = (selectedKeys: Key[], info: any) => {
    if (selectedKeys.length > 0) {
      const selectedKey = selectedKeys[0] as string;
      setSelectedTreeKey(selectedKey);
      
      if (selectedKey === "uncategorized") {
        // 显示未分类文件
        setSelectedCourse(null);
        loadResources({ courseId: "" }); // 空字符串表示未分类
      } else if (selectedKey.startsWith('course-')) {
        const courseId = selectedKey.split('-')[1];
        if (courseId) {
          setSelectedCourse(courseId);
          loadResources({ courseId });
        }
      } else if (selectedKey.startsWith('resource-')) {
        const resourceId = selectedKey.split('-')[1];
        // 可以在这里处理单个资源的选择
      }
    }
  };

  // 表格列定义
  const columns = [
    {
      title: "资源名称",
      dataIndex: "name",
      key: "name",
      width: 250,
      ellipsis: true,
      render: (text: string, record: Resource) => (
        <Space>
          <ResourceIcon type={record.type}>
            {record.type === "folder" ? <FolderOutlined /> : <FileOutlined />}
          </ResourceIcon>
          <div>
            <Tooltip title={text}>
              <Text ellipsis style={{ maxWidth: 180 }}>
                {text}
              </Text>
            </Tooltip>
            {record.courseName && (
              <div style={{ fontSize: '12px', color: '#666' }}>
                {record.courseName}
              </div>
            )}
          </div>
          {record.isFavorite && <StarFilled style={{ color: '#faad14' }} />}
          {uploadingFiles[record.name] !== undefined && (
            <Progress percent={uploadingFiles[record.name]} size="small" />
          )}
        </Space>
      ),
    },
    {
      title: "分类",
      dataIndex: "category",
      key: "category",
      width: 100,
      render: (category: string) => {
        const colorMap = {
          "课件": "blue",
          "实验资料": "green",
          "试题资料": "orange",
          "视频资料": "purple",
          "其他": "default"
        };
        return <Tag color={colorMap[category as keyof typeof colorMap]}>{category}</Tag>;
      },
    },
    {
      title: "大小",
      dataIndex: "size",
      key: "size",
      width: 80,
    },
    {
      title: "上传时间",
      dataIndex: "uploadTime",
      key: "uploadTime",
      width: 100,
    },
    {
      title: "下载",
      dataIndex: "downloads",
      key: "downloads",
      width: 80,
      render: (downloads: number) => (
        <Badge count={downloads} showZero style={{ backgroundColor: '#52c41a' }} />
      ),
    },
    {
      title: "状态",
      dataIndex: "shared",
      key: "shared",
      width: 100,
      render: (shared: boolean, record: Resource) => (
        <Space>
          <Tag color={shared ? "green" : "default"}>
            {shared ? "已分享" : "未分享"}
          </Tag>
          {record.isFavorite && <StarFilled style={{ color: '#faad14' }} />}
        </Space>
      ),
    },
    {
      title: "操作",
      key: "action",
      width: 120,
      fixed: "right" as const,
      render: (_: any, record: Resource) => {
        const menuItems = [
          {
            key: "preview",
            icon: <EyeOutlined />,
            label: "预览",
            onClick: () => handlePreview(record),
          },
          {
            key: "download",
            icon: <DownloadOutlined />,
            label: "下载",
            onClick: () => handleDownload(record),
          },
          {
            key: "favorite",
            icon: record.isFavorite ? <StarFilled /> : <StarOutlined />,
            label: record.isFavorite ? "取消收藏" : "收藏",
            onClick: () => handleFavorite(record.id, record.isFavorite || false),
          },
          {
            key: "share",
            icon: <ShareAltOutlined />,
            label: record.shared ? "取消分享" : "分享",
            onClick: () => handleShare(record.id, record.shared),
          },
          {
            key: "edit",
            icon: <EditOutlined />,
            label: "编辑",
            onClick: () => {
              setSelectedResource(record.id);
              form.setFieldsValue(record);
              setIsModalVisible(true);
            },
          },
          {
            type: "divider" as const,
          },
          {
            key: "delete",
            icon: <DeleteOutlined />,
            label: "删除",
            danger: true,
            onClick: () => handleDelete(record.id),
          },
        ];

        return (
          <Space size="small">
            <Tooltip title="预览">
              <Button
                type="link"
                size="small"
                icon={<EyeOutlined />}
                onClick={() => handlePreview(record)}
              />
            </Tooltip>
            <Tooltip title={record.isFavorite ? "取消收藏" : "收藏"}>
              <Button
                type="link"
                size="small"
                icon={record.isFavorite ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
                onClick={() => handleFavorite(record.id, record.isFavorite || false)}
              />
            </Tooltip>
            <Dropdown
              menu={{ items: menuItems }}
              trigger={["click"]}
              placement="bottomRight"
            >
              <Button type="link" size="small" icon={<MoreOutlined />} />
            </Dropdown>
          </Space>
        );
      },
    },
  ];

  // 下载资源
  const handleDownload = async (record: Resource) => {
    try {
      message.success(`开始下载 ${record.name}`);
      // 模拟下载操作
      setTimeout(() => {
        message.success(`${record.name} 下载完成`);
      }, 2000);
    } catch (error) {
      console.error("下载失败:", error);
      message.error("下载失败");
    }
  };

  // 预览资源
  const handlePreview = async (record: Resource) => {
    setPreviewLoading(true);
    try {
      // 模拟预览加载
      await new Promise(resolve => setTimeout(resolve, 1000));
      setPreviewResource({
        ...record,
        url: "https://www.example.com/preview", // 模拟预览URL
      });
      setPreviewVisible(true);
    } catch (error) {
      console.error("预览失败:", error);
      message.error("预览失败");
    } finally {
      setPreviewLoading(false);
    }
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请选择要删除的资源");
      return;
    }

    confirm({
      title: "批量删除",
      content: `确定要删除选中的 ${selectedRowKeys.length} 个资源吗？`,
      async onOk() {
        try {
          const updatedResources = resources.filter(
            resource => !selectedRowKeys.includes(resource.id)
          );
          setResources(updatedResources);
          message.success("批量删除成功");
          setSelectedRowKeys([]);
        } catch (error) {
          console.error("批量删除失败:", error);
          message.error("批量删除失败");
        }
      },
    });
  };

  // 批量分享
  const handleBatchShare = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请选择要分享的资源");
      return;
    }

    try {
      const updatedResources = resources.map(resource =>
        selectedRowKeys.includes(resource.id)
          ? { ...resource, shared: true }
          : resource
      );
      setResources(updatedResources);
      message.success("批量分享成功");
      setSelectedRowKeys([]);
    } catch (error) {
      console.error("批量分享失败:", error);
      message.error("批量分享失败");
    }
  };

  const rowSelection: TableRowSelection<Resource> = {
    selectedRowKeys,
    onChange: (selectedKeys: Key[], selectedRows: Resource[]) => {
      setSelectedRowKeys(selectedKeys);
    },
  };

  // 获取统计数据
  const getStats = () => {
    const total = resources.length;
    const shared = resources.filter(r => r.shared).length;
    const favorites = resources.filter(r => r.isFavorite).length;
    const totalDownloads = resources.reduce((sum, r) => sum + r.downloads, 0);
    
    return { total, shared, favorites, totalDownloads };
  };

  const stats = getStats();

  return (
    <div style={{ padding: "24px" }}>
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总资源数"
              value={stats.total}
              prefix={<FileOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已分享"
              value={stats.shared}
              prefix={<ShareAltOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="收藏数"
              value={stats.favorites}
              prefix={<StarOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="总下载"
              value={stats.totalDownloads}
              prefix={<DownloadOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[24, 24]}>
        <Col xs={24} sm={24} md={6} lg={6} xl={6}>
          <StyledCard 
            title="资源目录" 
            extra={
              <Button 
                type="text" 
                icon={<ReloadOutlined />} 
                onClick={() => loadInitialData()}
              />
            }
          >
            <DirectoryTree
              defaultExpandAll
              treeData={getTreeData()}
              onSelect={handleTreeSelect}
              selectedKeys={selectedTreeKey ? [selectedTreeKey] : []}
            />
          </StyledCard>
        </Col>
        <Col xs={24} sm={24} md={18} lg={18} xl={18}>
          <StyledCard
            title={
              <Space>
                <span>资源列表</span>
                {selectedRowKeys.length > 0 && (
                  <Tag color="blue">{`已选择 ${selectedRowKeys.length} 项`}</Tag>
                )}
              </Space>
            }
            extra={
              <Space wrap>
                {selectedRowKeys.length > 0 ? (
                  <>
                    <Button
                      icon={<ShareAltOutlined />}
                      onClick={handleBatchShare}
                    >
                      批量分享
                    </Button>
                    <Button
                      danger
                      icon={<DeleteOutlined />}
                      onClick={handleBatchDelete}
                    >
                      批量删除
                    </Button>
                  </>
                ) : (
                  <>
                    <Button
                      icon={<CloudUploadOutlined />}
                      onClick={showUploadModal}
                    >
                      上传资源
                    </Button>
                    <Button
                      icon={<FolderAddOutlined />}
                      onClick={showModal}
                    >
                      新建文件夹
                    </Button>
                  </>
                )}
              </Space>
            }
          >
            {/* 搜索和筛选 */}
            <Card size="small" style={{ marginBottom: 16 }}>
              <Form layout="inline" onFinish={handleSearch}>
                <Form.Item name="keyword">
                  <Input
                    placeholder="搜索资源名称、描述或课程"
                    prefix={<SearchOutlined />}
                    style={{ width: 200 }}
                    allowClear
                  />
                </Form.Item>
                <Form.Item name="category">
                  <Select
                    placeholder="选择分类"
                    style={{ width: 120 }}
                    allowClear
                  >
                    <Option value="课件">课件</Option>
                    <Option value="实验资料">实验资料</Option>
                    <Option value="试题资料">试题资料</Option>
                    <Option value="视频资料">视频资料</Option>
                    <Option value="其他">其他</Option>
                  </Select>
                </Form.Item>
                <Form.Item name="type">
                  <Select
                    placeholder="文件类型"
                    style={{ width: 120 }}
                    allowClear
                  >
                    <Option value="ppt">PPT</Option>
                    <Option value="pdf">PDF</Option>
                    <Option value="doc">文档</Option>
                    <Option value="video">视频</Option>
                    <Option value="image">图片</Option>
                    <Option value="folder">文件夹</Option>
                  </Select>
                </Form.Item>
                <Form.Item name="courseId">
                  <Select
                    placeholder="选择课程"
                    style={{ width: 150 }}
                    allowClear
                  >
                    {courses.map(course => (
                      <Option key={course.id} value={course.id}>
                        {course.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                </Form.Item>
                <Form.Item>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Form.Item>
              </Form>
            </Card>

            {/* 标签页 */}
            <Tabs
              activeKey={activeTab}
              onChange={setActiveTab}
              style={{ marginBottom: 16 }}
            >
              <TabPane tab="全部资源" key="all" />
              <TabPane tab="我的收藏" key="favorites" />
              <TabPane tab="已分享" key="shared" />
              <TabPane tab="最近上传" key="recent" />
            </Tabs>

            {/* 上传区域 */}
            <UploadArea style={{ marginBottom: 16, display: selectedRowKeys.length > 0 ? "none" : "block" }}>
              <Upload.Dragger {...uploadProps}>
                <p className="ant-upload-drag-icon">
                  <CloudUploadOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                </p>
                <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                <p className="ant-upload-hint">
                  支持单个或批量上传，支持 PPT、PDF、文档、视频、图片等格式
                </p>
              </Upload.Dragger>
            </UploadArea>

            {/* 资源表格 */}
            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={resources}
              rowKey="id"
              scroll={{ x: 1000 }}
              loading={resourcesLoading}
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `${range[0]}-${range[1]} 共 ${total} 条`,
                onChange: (page, pageSize) => {
                  setPagination(prev => ({ ...prev, current: page, pageSize: pageSize || 10 }));
                },
              }}
            />
          </StyledCard>
        </Col>
      </Row>

      {/* 新建文件夹模态框 */}
      <Modal
        title={selectedResource ? "编辑资源" : "新建文件夹"}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="名称"
            rules={[{ required: true, message: "请输入名称" }]}
          >
            <Input placeholder="请输入文件夹名称" />
          </Form.Item>
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: "请选择分类" }]}
          >
            <Select placeholder="请选择分类">
              <Option value="课件">课件</Option>
              <Option value="实验资料">实验资料</Option>
              <Option value="试题资料">试题资料</Option>
              <Option value="视频资料">视频资料</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="courseId"
            label="所属课程"
          >
            <Select placeholder="请选择所属课程（可选，不选择将归类为未分类文件）" allowClear>
              {courses.map(course => (
                <Option key={course.id} value={course.id}>
                  {course.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="description" label="描述">
            <TextArea rows={4} placeholder="请输入描述信息" />
          </Form.Item>
          <Form.Item name="tags" label="标签">
            <Select mode="tags" placeholder="请输入标签">
              <Option value="重点">重点</Option>
              <Option value="难点">难点</Option>
              <Option value="基础">基础</Option>
              <Option value="进阶">进阶</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 上传配置模态框 */}
      <Modal
        title="上传资源"
        open={isUploadModalVisible}
        onOk={handleUploadOk}
        onCancel={handleUploadCancel}
        width={600}
      >
        <Form form={uploadForm} layout="vertical">
          <Form.Item
            name="category"
            label="资源分类"
            rules={[{ required: true, message: "请选择资源分类" }]}
          >
            <Select placeholder="请选择资源分类">
              <Option value="课件">课件</Option>
              <Option value="实验资料">实验资料</Option>
              <Option value="试题资料">试题资料</Option>
              <Option value="视频资料">视频资料</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="courseId"
            label="所属课程"
          >
            <Select placeholder="请选择所属课程（可选，不选择将归类为未分类文件）" allowClear>
              {courses.map(course => (
                <Option key={course.id} value={course.id}>
                  {course.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="description" label="资源描述">
            <TextArea rows={3} placeholder="请输入资源描述" />
          </Form.Item>
          <Form.Item name="tags" label="标签">
            <Select mode="tags" placeholder="请输入标签">
              <Option value="重点">重点</Option>
              <Option value="难点">难点</Option>
              <Option value="基础">基础</Option>
              <Option value="进阶">进阶</Option>
            </Select>
          </Form.Item>
          <Alert
            message="上传说明"
            description="支持的文件格式：PPT、PDF、Word、Excel、视频、图片等。单个文件大小不超过100MB。"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <Upload {...uploadProps}>
            <Button icon={<UploadOutlined />}>选择文件</Button>
          </Upload>
        </Form>
      </Modal>

      {/* 预览模态框 */}
      <Modal
        title={previewResource?.name}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width={1000}
        style={{ top: 20 }}
        bodyStyle={{ height: "calc(100vh - 200px)", padding: 0 }}
      >
        {previewLoading ? (
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>加载预览...</div>
          </div>
        ) : (
          <div style={{ 
            width: "100%", 
            height: "100%", 
            display: "flex", 
            alignItems: "center", 
            justifyContent: "center",
            background: "#f5f5f5"
          }}>
            <div style={{ textAlign: "center" }}>
              <FileOutlined style={{ fontSize: "48px", color: "#999" }} />
              <div style={{ marginTop: 16, color: "#666" }}>
                文件预览功能演示
              </div>
              <div style={{ marginTop: 8, color: "#999", fontSize: "12px" }}>
                {previewResource?.name}
              </div>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default TeacherResources;
